package com.itheima.reggie.service.iml;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    private SetmealService setmealService;
    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private CategoryService categoryService;

    /**
     * 新增保存套餐，同时需要保存套餐和菜品的关联关系
     *
     * @param setmealDto
     */
    @Override
    @Transactional
    public void saveWithDish(SetmealDto setmealDto) {
        //保存套餐的基本信息，操作setmeal，执行insert操作
        this.save(setmealDto);

        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes.forEach(item -> {
            item.setSetmealId(setmealDto.getId());
        });

        //保存套餐和菜品的关联信息，操作setmeal_dish,执行insert操作
        setmealDishService.saveBatch(setmealDishes);
    }


    /**
     * 套餐管理 分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @Override
    public Page<SetmealDto> pageR(int page, int pageSize, String name) {
        //分页条件查询
        Page<Setmeal> pageInfo = new Page<>(page, pageSize);

        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
        //根据名字模糊查询
        lqw.like(name != null, Setmeal::getName, name);
        //添加排序条件，根据更新时间降序排列
        lqw.orderByDesc(Setmeal::getUpdateTime);
        setmealService.page(pageInfo, lqw);


        Page<SetmealDto> dtoPage = new Page<>();
        //对象拷贝  原来的没有套餐分类名称
        BeanUtils.copyProperties(pageInfo, dtoPage, "records");
        List<Setmeal> records = pageInfo.getRecords();
        //存储查出来的套餐分类名称
        List<SetmealDto> list = new ArrayList<>();
        records.forEach(item -> {
            SetmealDto setmealDto = new SetmealDto();
            //对象拷贝
            BeanUtils.copyProperties(item, setmealDto);
            //分类id
            Long categoryId = item.getCategoryId();
            //根据分类id查询分类对象
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                //分类名称
                String categoryName = category.getName();
                setmealDto.setCategoryName(categoryName);
                list.add(setmealDto);
            }
        });
        dtoPage.setRecords(list);
        return dtoPage;
    }

    /**
     * 删除及批量删除套餐
     *
     * @param ids
     */
    @Override
    @Transactional
    public void removeWithDish(List<Long> ids) {
        //select count(*) from setmeal where id in (1,2,3) and status = 1
        //查询套餐状态，确定是否可用删除
        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
        lqw.in(Setmeal::getId, ids);
        //查询是否有售卖中的套餐被选中
        lqw.in(Setmeal::getStatus, 1);

        int count = this.count(lqw);
        if (count > 0) {
            //如果不能删除，抛出一个业务异常
            throw new CustomException("套餐正在售卖中,不能删除");
        }
        //如果可以删除，先删除套餐表中的数据---setmeal
        this.removeByIds(ids);

        //delete from setmeal_dish where setmeal_id in (1,2,3)
        LambdaQueryWrapper<SetmealDish> SDLqw = new LambdaQueryWrapper<>();
        SDLqw.in(SetmealDish::getSetmealId, ids);
        //删除关系表中的数据----setmeal_dish
        setmealDishService.remove(SDLqw);
    }

    /**
     * 修改套餐 数据的回写
     *
     * @param id
     * @return
     */
    @Override
    public SetmealDto getByIdWithcategory(Long id) {
        //基本信息 不包含该套餐属于哪个套餐分类
        Setmeal setmeal = this.getById(id);
        //查询套餐所属的套餐分类id
        Long categoryId = setmeal.getCategoryId();
        //查询套餐关联的菜品
        LambdaQueryWrapper<SetmealDish> setmealDishLqw = new LambdaQueryWrapper<>();
        setmealDishLqw.eq(SetmealDish::getSetmealId, id);
        List<SetmealDish> list = setmealDishService.list(setmealDishLqw);
        //存储用来返回的套餐信息集合
        SetmealDto setmealDto = new SetmealDto();
        //基本信息复制
        BeanUtils.copyProperties(setmeal, setmealDto);
        //菜品信息复制
        setmealDto.setSetmealDishes(list);
        //查询所属的套餐名字
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Category::getId, categoryId);
        Category category = categoryService.getOne(lqw);
        String categoryName = category.getName();
        //赋值套餐名字
        setmealDto.setCategoryName(categoryName);

        return setmealDto;
    }

    /**
     * 修改套餐 保存修改套餐
     *
     * @param setmealDto
     */
    @Override
    public void updateIdWithcategory(SetmealDto setmealDto) {
        //更新基本信息
        this.updateById(setmealDto);
        //把原始的关联菜品删除
        LambdaQueryWrapper<SetmealDish> setmealDishLqw = new LambdaQueryWrapper<>();
        setmealDishLqw.eq(SetmealDish::getSetmealId, setmealDto.getId());
        setmealDishService.remove(setmealDishLqw);
        //新的关联菜品信息
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        for (SetmealDish setmealDish : setmealDishes) {
            //给每个菜品关联套餐id
            setmealDish.setSetmealId(setmealDto.getId());
        }
        //保存套餐的菜品信息
        setmealDishService.saveBatch(setmealDishes);
    }
}
